package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.FollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author DiXiaoNie
 * @since 2023/1/3 11:27
 */
@Service
public class FollowBehaviorServiceImpl implements FollowBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 关注或取消关注
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/03
     */
    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {
        //1.参数校验
        if (dto == null || dto.getAuthorId() == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取用户登录ID
        ApUser apUser = ApThreadLocalUtil.getApUserThreadLocal();
        if (apUser == null || apUser.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.判断当前用户是否关注过当前作者 查询redis
        String followKey = "USER_FOLLOW_" + apUser.getId();
        String fansKey = "USER_FANS_" + dto.getAuthorId();

        Boolean followFlag = redisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());
        // 3.1 如果关注过，而此时的动作还是关注行为， operation = 0 则取消返回
        if (followFlag && dto.getOperation() == 0) {
            return ResponseResult.errorResult(5001, "您已关注过此作者");
        }
        if (!followFlag && dto.getOperation() == 1) {
            return ResponseResult.errorResult(5001, "您还没有关注过此作者，请先关注在进行此操作");
        }
        // 3.2 如果关注过，而此时的动作是取消关注行为，operation = 1 则删除redis和mongo
        if (followFlag && dto.getOperation() == 1) {
            //删除redis
            this.redisTemplate.opsForHash().delete(followKey, dto.getAuthorId().toString());
            this.redisTemplate.opsForHash().delete(fansKey, apUser.getId().toString());
            //删除mongo
            this.mongoTemplate.remove(Query.query(
                    Criteria.where("userId").is(apUser.getId()).and("followId").is(dto.getAuthorId())
            ), ApFollowBehavior.class);
            return ResponseResult.okResult("取消关注成功");
        }
        // 3.2 如果没有关注过，而此时的动作是关注行为，operation = 0 则新增redis和mongo
        if (!followFlag && dto.getOperation() == 0) {
            //新增redis
            this.redisTemplate.opsForHash().put(followKey, dto.getAuthorId().toString(), "1");
            this.redisTemplate.opsForHash().put(fansKey, apUser.getId().toString(), "1");
            //新增mongo
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setFollowId(dto.getAuthorId());
            apFollowBehavior.setCreatedTime(new Date());
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setUserId(Long.valueOf(apUser.getId()));
            this.mongoTemplate.insert(apFollowBehavior);
        }
        return ResponseResult.okResult("关注成功");
    }
}
